<template>
  <div>
    <div class="tabs">
      <div class="tabs-header">
        <div class="tabs-nav-wrap" ref="tabWrap">
          <draggable v-model="tabList" :move="draggableMove" :options="{draggable: '.tab-item', chosenClass: 'sortable-chosen'}" class="tabs-nav" style="transform: translateX(0px);">
            <div v-for="tab in tabList" :key="tab.id" @click="selectTab(tab.id)" @mouseover="showClose(tab.id)" @mouseout="hideClose(tab.id)" :class="{'is-active': tab.id === currentTab}" class="tab-item">
              <span class="tab-title">{{ tab.title }}</span>
              <img v-if="!tab.panel.saveStatus && !tab.showClosing" class="icon-point" :src="icon.point" />
              <img v-if="tab.showClosing" @click.stop="closeTab(tab.id)" class="icon-point" :src="icon.close" />
            </div>
          </draggable>
        </div>
      </div>
      <div class="tab-content" :style="{height: tabContentHeight + 'px'}" ref="tabContent">
        <mavon-editor v-for="tab in tabList" :key="tab.panel.id" v-model="tab.panel.content" @save="saveFile" class="editor" role="tabpanel" :id="tab.panel.id" :style="{display: tab.id === currentTab ? 'flex' : 'none'}"/>
      </div>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import fs from 'fs'
import path from 'path'

import icon from '@/assets/js/icon'

const { ipcRenderer } = require('electron')
const { dialog } = require('electron').remote
let newLen = 1
export default {
  data () {
    return {
      icon,
      tabList: [],
      value: '# hello',
      currentTab: 'tab-0',
      sortableOpt: {
        dragClass: 'tab-item'
      }
    }
  },
  methods: {
    openRightMenu () {
      ipcRenderer.send('show-context-menu')
    },
    showClose (id) {
      this.tabList.forEach(tab => {
        if (tab.id === id) {
          tab.showClosing = true
        } else {
          tab.showClosing = false
        }
      })
    },
    hideClose (id) {
      this.tabList.forEach(tab => {
        if (tab.id === id) {
          tab.showClosing = false
        }
      })
    },
    selectTab (id) {
      this.currentTab = id
    },
    closeTab (id) {
      const index = this.tabList.findIndex(tab => {
        return tab.id === id
      })
      // 如果关闭的是当前页面
      if (this.tabList[index].id === this.currentTab) {
        if (index === (this.tabList.length - 1)) {
          this.currentTab = this.tabList[0].id
        } else {
          this.currentTab = this.tabList[index + 1].id
        }
      }
      this.tabList.splice(index, 1)
      const _self = this
      _self.$nextTick(() => {
        if (_self.$refs.tabWrap.offsetHeight - _self.$refs.tabWrap.clientHeight) {
          _self.$refs.tabWrap.scrollLeft = _self.$refs.tabWrap.clientWidth
        }
      })
    },
    draggableMove (evt, originalEvent) {
      this.currentTab = evt.draggedContext.element.id
    },
    newFileListener () {
      const _self = this
      ipcRenderer.on('new-file', (event, arg) => {
        const id = 'tab-' + _self.tabList.length
        const panelId = 'panel-' + _self.tabList.length
        _self.tabList.push({
          id: id,
          title: '新建文件' + newLen,
          showClosing: false,
          panel: {
            id: panelId,
            saveStatus: false
          }
        })
        _self.currentTab = id
        newLen++
        _self.$nextTick(() => {
          if (_self.$refs.tabWrap.offsetHeight - _self.$refs.tabWrap.clientHeight) {
            _self.$refs.tabWrap.scrollLeft = _self.$refs.tabWrap.clientWidth
          }
        })
      })
    },
    openFileListener () {
      const _self = this
      ipcRenderer.on('open-file', (event, arg) => {
        let filepath = ''
        if (arg instanceof Array) {
          filepath = arg[0]
        } else if (typeof arg === 'string') {
          filepath = arg
        } else {
          return
        }
        const exitsIndex = _self.tabList.findIndex(tab => {
          return tab.src === filepath
        })
        if (exitsIndex > -1) {
          _self.currentTab = _self.tabList[exitsIndex].id
          return
        }
        const index = _self.tabList.findIndex(tab => {
          return tab.title === 'untitled'
        })
        const filename = path.basename(filepath, '.md')
        if (index > -1) {
          _self.tabList[index].title = filename
          _self.tabList[index].src = filepath
        } else {
          const tabId = 'tab-' + _self.tabList.length
          _self.tabList.push({
            id: tabId,
            title: filename,
            src: filepath,
            showClosing: false,
            panel: {
              id: 'panel-0',
              content: '',
              saveStatus: false
            }
          })
          _self.currentTab = tabId
        }
        fs.readFile(filepath, function (err, data) {
          if (err) throw err
          _self.tabList.forEach(tab => {
            if (tab.id === _self.currentTab) {
              tab.panel.content = data.toString()
            }
          })
          _self.insertOpenFileRecord(filename, filepath)
        })
      })
    },
    insertOpenFileRecord (fileName, src) {
      let openFileRecord = []
      this.db.find({
        name: 'openFileRecord'
      }, (err, data) => {
        if (err) throw err
        openFileRecord = data[0].recordList
        const index = openFileRecord.findIndex(item => {
          return item.src === src
        })
        if (index > -1) {
          // 更新
          openFileRecord[index].openTime = new Date()
        } else {
          openFileRecord.push({
            filename: fileName,
            src: src,
            openTime: new Date()
          })
        }
        openFileRecord.sort((o1, o2) => {
          return o2.openTime.getTime() - o1.openTime.getTime()
        })
        this.db.update({
          name: 'openFileRecord'
        }, {
          $set: {
            recordList: openFileRecord
          }
        }, (err, data) => {
          if (err) throw err
        })
      })
    },
    saveFile (value, render) {
      this.tabList.forEach(tab => {
        if (tab.id === this.currentTab) {
          if (tab.src) {
            fs.writeFile(tab.src, value, (e, data) => {
              alert('保存成功！！！')
              this.insertOpenFileRecord(path.basename(tab.src), tab.src)
            })
          } else {
            dialog.showSaveDialog({
              title: '保存文件',
              defaultPath: tab.title,
              filters: [
                {name: 'Markdowns', extensions: ['md']}
              ]
            }, (filepath) => {
              const filename = path.basename(filepath, '.md')
              fs.writeFile(filepath, value, (e, data) => {
                alert('保存成功！！！')
                this.insertOpenFileRecord(path.basename(tab.src), tab.src)
              })
              tab.panel.src = filepath
              tab.title = filename
            })
          }
          tab.panel.saveStatus = true
        }
      })
      // dialog.showOpenDialog()
    }
  },
  components: {
    draggable
  },
  mounted () {
    if (this.tabList.length === 0) {
      const id = 'tab-0'
      this.tabList.push({
        id: id,
        title: 'untitled',
        showClosing: false,
        panel: {
          id: 'panel-0',
          content: '',
          saveStatus: false
        }
      })
    }
    ipcRenderer.send('menu-file')
    this.newFileListener()
    this.openFileListener()
    this.db.find({
      name: 'openFileRecord'
    }, (err, data) => {
      if (err) throw err
      ipcRenderer.send('open-file-record', data[0].recordList)
    })
    // 窗口变化监听
    const _self = this
    _self.resizable = true
    window.onresize = () => {
      if (_self.resizable) {
        _self.resizable = false
        setTimeout(() => {
          _self.$refs.tabContent.style.height = (window.innerHeight - _self.$refs.tabContent.offsetTop) + 'px'
          _self.resizable = true
        }, 400)
      }
    }
  },
  computed: {
    // 添加滚动条的时候
    tabContentHeight () {
      if (typeof this.$refs.tabContent === 'undefined') {
        return window.innerHeight - 32
      }
      return window.innerHeight - this.$refs.tabContent.offsetTop
    }
  }
}
</script>

<style>
.v-note-wrapper .v-note-op .left .op-icon, .v-note-wrapper .v-note-op .right .op-icon {
  font-size: 13px;
}
</style>

<style lang="stylus" scoped>
.sortable-chosen {
  background-color: #aceca1;
}
.tabs {
  box-shadow: rgba(0, 0, 0, 0.12) 0px 2px 4px 0px, rgba(0, 0, 0, 0.04) 0px 0px 6px 0px;
  background: rgb(255, 255, 255);
  border-width: 1px;
  border-style: solid;
  border-color: rgb(220, 223, 230);
  border-image: initial;
  .tabs-header {
    position: relative;
    padding: 0px;
    background-color: rgb(245, 247, 250);
    border-bottom: 1px solid rgb(228, 231, 237);
    margin: 0px;

    .tabs-nav-wrap {
      overflow-y: hidden;
      overflow-x: auto;
      margin-bottom: -1px;
      position: relative;
      .tabs-nav {
        white-space: nowrap;
        position: relative;
        float: left;
        z-index: 2;
        transition: transform 0.3s, -webkit-transform 0.3s;

        .tab-item {
          color: rgb(144, 147, 153);
           background-color: rgb(245, 247, 250);
          transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
          border-width: 1px;
          border-style: solid;
          border-color: transparent;
          border-right-color: #dcdfe6;
          border-image: initial;
          margin: -1px -1px 0px;
          padding-left: 12px;
          padding-right: 25px;
          font-size: 13px;
          height: 30px;
          line-height: 30px;
          box-sizing: border-box;
          display: inline-block;
          font-weight: 500;
          color: rgb(48, 49, 51);
          position: relative;
          list-style: none;
          
          .icon-point {    
            position: absolute;
            top: 7px;
            right: 6px;
            width: 13px;
            height: 13px;
          }
        }
        .is-active {
            color: #409eff;
            background-color: #fff;
            border: 1px solid transparent
            border-left-color: #dcdfe6;
            border-right-color: #dcdfe6;
            transition: all .3s cubic-bezier(.645,.045,.355,1);
            margin: -1px -1px 0;
          }
      }

      /*---滚动条默认显示样式--*/  
      &::-webkit-scrollbar-thumb{  
        background-color: #909399;  
        height:50px;  
        outline-offset:-2px;  
        outline:2px solid #fff;  
        -webkit-border-radius:4px;  
        border-bottom: 2px solid #fff;
      }  
      /*---鼠标点击滚动条显示样式--*/  
      &::-webkit-scrollbar-thumb:hover{  
        background-color: #018EE8;  
        height:50px;  
        -webkit-border-radius:4px; 
      }  
      /*---滚动条大小--*/  
      &::-webkit-scrollbar{  
        width: 6px;  
        height: 6px; 
      }  
      /*---滚动框背景样式--*/  
      &::-webkit-scrollbar-track-piece{  
        background-color:#fff;  
        -webkit-border-radius:0;  
      } 
      // CSS里面hover是设置鼠标放上链接的颜色，同样的，active也可以设置鼠标点击的颜色，只要到上面的代码添加如下代码就行了。
      &::-webkit-scrollbar-thumb:active{
          height:50px;
          background-color: #018EE8;
          -webkit-border-radius:4px;
      }  

    }
  }

  .tab-content {
    overflow: hidden;
    position: relative;
  }
}
.editor {
  height: 100%;
  padding: 0;
}
</style>

